<template>
  <div class="page-card">
    <div class="table-toolbar">
      <el-input
        v-model="search"
        placeholder="输入课程名称或代码"
        clearable
        style="max-width: 240px"
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="openDialog()">
        <el-icon><Plus /></el-icon>
        新增课程
      </el-button>
    </div>

    <el-table :data="courses" border v-loading="loading">
      <el-table-column prop="course_code" label="课程代码" width="120" />
      <el-table-column prop="course_name" label="课程名称" width="200" />
      <el-table-column label="课程类型" width="120">
        <template #default="{ row }">
          {{ getCourseTypeText(row.course_type) }}
        </template>
      </el-table-column>
      <el-table-column prop="credit" label="学分" width="80" />
      <el-table-column prop="course_hours" label="学时" width="80" />
      <el-table-column prop="grade_range" label="适用年级" width="100" />
      <el-table-column prop="course_desc" label="课程描述" width="200" show-overflow-tooltip />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="openDialog(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="pagination.size"
        :current-page="pagination.page"
        :total="pagination.total"
        @current-change="handlePageChange"
      />
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="课程代码" prop="course_code">
          <el-input v-model="form.course_code" />
        </el-form-item>
        <el-form-item label="课程名称" prop="course_name">
          <el-input v-model="form.course_name" />
        </el-form-item>
        <el-form-item label="课程类型" prop="course_type">
          <el-select v-model="form.course_type">
            <el-option v-for="item in courseTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="适用年级" prop="grade_range">
          <el-input v-model="form.grade_range" />
        </el-form-item>
        <el-form-item label="学分" prop="credit">
          <el-input-number v-model="form.credit" :min="0.5" :max="10" :step="0.5" />
        </el-form-item>
        <el-form-item label="学时" prop="course_hours">
          <el-input-number v-model="form.course_hours" :min="16" :max="128" />
        </el-form-item>
        <el-form-item label="课程描述" prop="course_desc">
          <el-input v-model="form.course_desc" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option v-for="item in courseStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { createCourse, deleteCourse, getCourseList, updateCourse } from '@/api/academic'
import type { Course } from '@/types/academic'
import { courseStatusOptions, courseTypeOptions } from '@/constants/options'

const loading = ref(false)
const saving = ref(false)
const courses = ref<Course[]>([])
const search = ref('')
const pagination = reactive({ page: 1, size: 10, total: 0 })

const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const form = reactive({
  id: 0,
  course_code: '',
  course_name: '',
  course_type: 1,
  grade_range: '',
  credit: 2,
  course_hours: 32,
  course_desc: '',
  status: 1
})

const rules: FormRules = {
  course_code: [{ required: true, message: '请输入课程代码', trigger: 'blur' }],
  course_name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }]
}

const dialogTitle = computed(() => (isEdit.value ? '编辑课程' : '新增课程'))

// 获取课程类型文本
const getCourseTypeText = (type: number) => {
  const courseType = courseTypeOptions.find(item => item.value === type)
  return courseType ? courseType.label : '未知类型'
}

const loadCourses = async () => {
  loading.value = true
  try {
    const skip = (pagination.page - 1) * pagination.size
    const res = await getCourseList({ skip, limit: pagination.size })
    const keyword = search.value.trim().toLowerCase()
    courses.value = res.items.filter((item: any) => {
      if (!keyword) return true
      return (
        item.course_name.toLowerCase().includes(keyword) ||
        item.course_code.toLowerCase().includes(keyword) ||
        (item.grade_range && item.grade_range.toLowerCase().includes(keyword))
      )
    })
    pagination.total = keyword ? courses.value.length : res.total
  } catch (error: any) {
    ElMessage.error(error?.message || '加载课程数据失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadCourses()
}

const handleSearch = () => {
  pagination.page = 1
  loadCourses()
}

const resetForm = () => {
  Object.assign(form, {
    id: 0,
    course_code: '',
    course_name: '',
    course_type: 1,
    grade_range: '',
    credit: 2,
    course_hours: 32,
    course_desc: '',
    status: 1
  })
  formRef.value?.clearValidate()
}

const openDialog = (row?: Course) => {
  resetForm()
  if (row) {
    isEdit.value = true
    Object.assign(form, row)
  } else {
    isEdit.value = false
  }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  saving.value = true
  try {
    if (isEdit.value) {
      await updateCourse(form.id, { 
        ...form,
        course_type: 1
      })
    } else {
      await createCourse({ ...form } as any)
    }
    ElMessage.success('保存成功')
    dialogVisible.value = false
    loadCourses()
  } catch (error: any) {
    ElMessage.error(error?.message || '保存失败')
  } finally {
    saving.value = false
  }
}

const handleDelete = async (row: Course) => {
  await ElMessageBox.confirm(`确认删除课程【${row.course_name}】吗？`, '提示', { type: 'warning' })
  try {
    await deleteCourse(row.id)
    ElMessage.success('已删除')
    loadCourses()
  } catch (error: any) {
    ElMessage.error(error?.message || '删除失败')
  }
}

onMounted(() => {
  loadCourses()
})
</script>

<style scoped lang="scss">
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: var(--spacing-md);
}
</style>